<template>
  <div>
    <div style="padding: 5px">
      <el-button type="danger" size="small" :disabled="selection.length === 0">删除</el-button>

      <el-button type="primary"
                 icon="el-icon-plus"
                 size="small"
                 @click="$ke_router.push({ name: 'NewsEdit', query: { id: '0' } })">
        发布新文章
      </el-button>
    </div>

    <el-table :data="list" v-loading="loading" @selection-change="onSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column prop="id" label="文章ID" width="80"/>

      <el-table-column prop="title" label="文章标题"/>

      <el-table-column prop="nickname" label="作者" width="100"/>

      <el-table-column prop="create_time" label="创建时间" width="180"/>

      <el-table-column label="操作" width="260" align="center">
        <template slot-scope="{ row }">
          <el-button size="small" type="info"
                     icon="el-icon-edit"
                     @click="$ke_router.push({ name: 'NewsEdit', query: { id: row.id } })">编辑</el-button>

          <el-button size="small" type="danger"
                     icon="el-icon-delete" @click="onClickDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="page" :total="total" @current-change="onPageChange"/>
  </div>
</template>

<script>
import { Vue, Component } from 'vue-property-decorator'

@Component
export default class NewsIndex extends Vue {
  list = []
  total = 0
  page = 1
  limit = 10
  selection = []
  loading = true


  mounted () {
    this.onLoad()
  }

  onPageChange (page) {
    this.list = []
    this.page = page
    this.onLoad()
  }

  // 加载列表数据
  onLoad () {
    this.loading = true
    this.$http.get('admin/news', { page: this.page })
      .finally(() => this.loading = false)
      .then(result => {
        this.list = result.list
        this.total = result.total
      })
  }

  // 表格选择项被改变
  onSelectionChange (data) {
    this.selection = data.map(item => {
      return item.id
    })
  }

  // 发布
  onPublish (row) {
    row.status = 1
    this.$message.success('发布成功')
  }

  // 删除
  onClickDelete (row) {
    this.$confirm('确定要删除这篇文章吗？')
      .then(() => {
        const idx = this.list.findIndex(item => item.id === row.id)
        this.list.splice(idx, 1)
        this.$http.delete(`admin/news/${row.id}`)
          .then((result) => {
            if (result.res_code === 0) {
              this.$message.success('删除成功')
              if (this.list.length <= 3) {
                this.list = []
                this.total = 0
                this.onLoad()
              }
            } else {
              this.onLoad()
            }
          })
      })
  }

}
</script>

<style scoped>

</style>
